package leetcode;


import java.util.HashMap;
import java.util.Map;

public class LC32 {
    public static void main(String[] args) {

    }
    public Node copyRandomList(Node head) {
        if (head == null) return null;
        Map<Node,Integer> map = new HashMap<>();
        int i = 0;
        Node temp = head;
        while(temp != null){
            map.put(temp,i++);
            temp = temp.next;
        }
        Node[] nodes = new Node[i];
        temp = head;
        i = 0;
        while(temp != null){
            nodes[i++] = new Node(temp.val);
            temp = temp.next;
        }
        temp = head;
        i = 0;
        while (temp != null){
            Node x = nodes[i];
            Integer nextI = map.get(temp.next);
            x.next = nodes[nextI];
            Integer randomI = map.get(temp.random);
            if (randomI != null) x.random = nodes[randomI];
            else x.random = null;
            temp = temp.next;
        }
        return nodes[0];
    }
}
class Node{
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
    }
    public Node(int val, Node next, Node random) {
        this.val = val;
        this.next = next;
        this.random = random;
    }
    public static Node in(int[][] x){
        Node node = new Node(x[0][0]);
        return node;
    }
}